import isPlainObject from './utils/isPlainObject';
import ActionTypes from './utils/actionTypes';
function createStore(reducer, preloadedState){
    if(typeof reducer !== 'function'){
        //reducer必须是一个函数
        throw new Error('reducer must be a function');
    }
    let currentState = preloadedState;
    let currentReducer = reducer;
    let currentListener = [];
    let getState = () => {
        return currentState;
    };
    let dispatch = (action) => {
        //action必须是一个纯对象
        if(!isPlainObject(action)){
            throw new Error('action must be a plain object');
        }
        if(typeof action.type === 'undefined'){
            throw new Error('type must be undefined');
        }
        currentState = currentReducer(currentState, action);
        //执行监听
        currentListener.forEach(fn => fn());
        //返回派发的action
        return action;
    };
    //订阅
    let subscribe = (listener) => {
        let subscribed = true;
        currentListener.push(listener);
        //返回一个取消订阅的函数
        return () => {
            //防止多次掉用取消操作
            if(!subscribed) return;
            //取消订阅：unsubscribe
            currentListener = currentListener.filter(fn => fn !== listener);
            subscribed = false;
        }
    };
    //默认触发，初始化state(initState可能在用户那里定义了)
    dispatch({type:ActionTypes.init});
    return {
        getState,
        dispatch,
        subscribe
    }
}
export default createStore;